package com.zhangjianling.premp.server.sys.impl;

import com.zhangjianling.premp.dao.sys.SysDictDao;
import com.zhangjianling.premp.entity.sys.Dictionary;
import com.zhangjianling.premp.server.sys.SysDictService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class SysDictServiceImpl implements SysDictService {

	@Resource
	private SysDictDao sysDictDao;
	
	@Resource
	private JdbcTemplate jdtemp;
	@Override
	public Page<Dictionary> pageList(int pageNumber, int pageSize, String sortColom,final Dictionary dict) {
		Pageable pageable = new PageRequest(pageNumber-1, pageSize, Sort.Direction.ASC,sortColom); 
		Page<Dictionary> sysDict = sysDictDao.findAll(new Specification<Dictionary>(){  
	            @Override  
	            public Predicate toPredicate(Root<Dictionary> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {  
	            	 List<Predicate> list = new ArrayList<Predicate>();  
	                 if(StringUtils.isNotBlank(dict.getName())){  
	                     list.add(criteriaBuilder.like(root.get("name").as(String.class), "%" +dict.getName()+"%"));  
	                 }  
	                 Predicate[] p = new Predicate[list.size()];  
	                 return criteriaBuilder.and(list.toArray(p));
	            }  
	        },pageable); 
		 return sysDict;
	}

	@Override
	public Dictionary saveDict(Dictionary dept) {
		return sysDictDao.save(dept);
	}

	@Override
	public void deleteDict(String id) {
		Dictionary dictionary = new Dictionary();
		dictionary.setDictId(id);
		sysDictDao.delete(dictionary);
	}

	@Override
	public Dictionary findDict(String id) {
		return sysDictDao.findById(id).get();
	}


	@Override
	public List<Dictionary> findTopList() {
		return sysDictDao.findTopList();
	}
	
	@Override
	public List<Map<String,Object>> findAll() {
		return jdtemp.queryForList("select t.dict_id ,t.name,t.pid ,t.open from sys_dict t  order by t.dict_id desc");
	}

	@Override
	public List<Dictionary> getChildres(String parentId) {
		return sysDictDao.getChildres(parentId);
	}
}
